//
// Created by deanw on 2025/6/22.
//

#include "image_scene.h"
#include <QGraphicsPixmapItem>
#include <QGraphicsSceneMouseEvent>

ImageScene::ImageScene(QObject* parent)
    : QGraphicsScene(parent)
{
}

bool ImageScene::setImage(const QImage& image, const QPointF& topLeft)
{
    if (image.isNull()) return false;
    //
    clear();
    //
    const auto pixelTopLeft = physicalToPixel(topLeft);
    const auto bitmap       = addPixmap(QPixmap::fromImage(image));
    bitmap->setPos(pixelTopLeft);
    bitmap->setZValue(INT32_MIN);
    const auto rect = bitmap->boundingRect().translated(pixelTopLeft);
    setSceneRect(rect);
    //
    return true;
}

void ImageScene::setDPI(const qreal dpi, const Axis axis)
{
    if (axis == X && !qFuzzyCompare(m_dpiX, dpi)) {
        m_dpiX = dpi > 0 ? dpi : 96;
        Q_EMIT dpiChanged(X);
    } else if (axis == Y && !qFuzzyCompare(m_dpiY, dpi)) {
        m_dpiY = dpi > 0 ? dpi : 96;
        Q_EMIT dpiChanged(Y);
    }
}

void ImageScene::setDPM(qreal pixelsPerMM, Axis axis)
{
    const auto dpi = pixelsPerMM * 25.4;
    setDPI(dpi, axis);
}

qreal ImageScene::dpi(const Axis axis) const
{
    if (axis == X)
        return m_dpiX;
    else
        return m_dpiY;
}

QSizeF ImageScene::physicalSize() const
{
    const auto rc = sceneRect().toRect();
    const auto w  = pixelsToMM(rc.width(), ImageScene::X);
    const auto h  = pixelsToMM(rc.height(), ImageScene::Y);
    return { w, h };
}

void ImageScene::addPhysicalMarker(const QPointF& physPos, const QString& label)
{
    const auto pixPos = physicalToPixel(physPos);
    addEllipse(pixPos.x() - 5,
               pixPos.y() - 5,
               10,
               10,
               QPen(Qt::red, 2),
               QBrush(Qt::yellow));

    const auto text = addText(label);
    text->setPos(pixPos);
    text->setDefaultTextColor(Qt::white);

    // 获取文字项的边界矩形
    const auto textRect = text->boundingRect();

    // 创建一个半透明背景矩形
    const auto background = new QGraphicsRectItem(textRect, text);
    background->setPos(text->pos());
    background->setBrush(QColor(0, 0, 0, 128)); // 半透明背景
    background->setPen(Qt::NoPen);              // 无边框
}

void ImageScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
{
    QGraphicsScene::mouseDoubleClickEvent(event);
    const auto scenePos    = event->scenePos();
    const auto physicalPos = pixelToPhysical(scenePos.toPoint());
    Q_EMIT doubleClicked(physicalPos);
}
